import { changeCount, getCartList, deleteSelect } from '@/api/cart'
import { Toast } from 'vant'
export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    getCartList (state, newList) {
      state.cartList = newList
    },
    toggleCheck (state, goodsId) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    toggleAllCheck (state, newValue) {
      state.cartList.forEach(item => {
        item.isChecked = newValue
      })
    },
    changeCount (state, { goodsId, value }) {
      const obj = state.cartList.find(item => item.goods_id === goodsId)
      obj.goods_num = value
    }
  },
  actions: {
    async getCartAction (context) {
      const { data } = await getCartList()
      data.list.forEach(element => {
        element.isChecked = true
      })
      context.commit('getCartList', data.list)
    },
    async changeCountAction (context, obj) {
      const { value, goodsId, skuId } = obj
      context.commit('changeCount', {
        goodsId,
        value
      })
      await changeCount(goodsId, value, skuId)
    },
    // 删除购物车数据
    async deleteSelectAction (context) {
      const selectCartList = context.getters.selectCartList
      const cartIds = selectCartList.map(item => item.id)
      await deleteSelect(cartIds)
      Toast('删除成功')
      // 重新拉取最新的购物车数据（重新渲染）
      context.dispatch('getCartAction')
    }
  },
  getters: {
    // 商品总数
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => {
        return sum + item.goods_num
      }, 0)
    },
    // 选中的商品列表
    selectCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 选中的商品总数
    selectCount (state, getters) {
      return getters.selectCartList.reduce((sum, item) => {
        return sum + item.goods_num
      }, 0)
    },
    // 选中的商品总价
    selectPrice (state, getters) {
      return getters.selectCartList.reduce((sum, item) => {
        return sum + item.goods_num * item.goods.goods_price_min
      }, 0).toFixed(2)
    },
    // 全选
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
